﻿using Gds.Model.ConfigModel.Controller;
using Gds.Model.ConfigModel.GasMeter;
using Gds.Utility.Helper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Gds.Model.ConfigModel.CommuEquip
{
    public class CommuTool_ES2000_D : IcommuTool
    {
        public string MainAddress { get; set; }
        public string ControlCode { get; set; }
        public string TotalLineNumber { get; set; }
        public int ItemLenth { get; set; }
        public string ItemValue { get; set; }
        public string CalaValue { get; set; }
        public bool WriteDataFlag { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
        public bool StopSend { get; set; }
        public bool RetrunEmpty { get; set; }
        public SerialHelper SerialHelper { get; set; }
        public Dictionary<int, GasSaveModel> realTimeValue { get; set; }
        public Dictionary<int, GasSaveModel> lastTimerealTimeValue { get; set; }
        public bool IsFinishSendData { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
        public bool CanCommunication { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
        public bool IsSendNoVice { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
        public bool IsSendReset { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
        public bool IsSendNoViceResult { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
        public bool IsSendResetResult { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }


        public int ControllerFailTime { get; set; }

        public int ControllerFailMaxTime { get; set; }

        public int ChannelDataLength { get; set; }
        public int StartIndex { get; set; }
        public int ReadLength { get; set; }
        public List<string> SendCodeList { get; set; }
        public int NeedReadLength { get; set; }
        public Dictionary<int, string> KeepingDic { get; set; }
        public Dictionary<int, string> InputDic { get; set; }
        public bool IsCanSet { get; set; }

        public event EventHandler AddLogEventHandler;
        public event EventHandler AddErrorLogEventHandler;
        public event EventHandler AddRunStateModelEventHandler;
        /// <summary>
        /// 通道探头单位
        /// </summary>
        List<GasChannalConfig> listGasChannalConfig = new List<GasChannalConfig>();
        /// <summary>
        /// 解析报文，将数据保存到寄存器字典中
        /// </summary>
        /// <param name="Code"></param>
        /// <param name="startIndex"></param>
        public void AnalyzeCode(string Code, int startIndex)
        {
            try
            {
                //初始化两个寄存器存储字典
                if (KeepingDic == null) KeepingDic = new Dictionary<int, string>();
                if (InputDic == null) InputDic = new Dictionary<int, string>();
                var trimString = Code.Replace(" ", "");
                var ChangeString = "";
                for (int i = 0; i < trimString.Length; i = i + 2)
                {
                    var tmpFrame = trimString.Substring(i, 2);
                    ChangeString = ChangeString + tmpFrame + " ";
                }
                ChangeString = ChangeString.Substring(0, ChangeString.Length - 1);

                var codeList = ChangeString.Split(' ');
                if (codeList.Length < 3)
                {
                    return;
                }
                MainAddress = Convert.ToInt32(codeList[0], 16).ToString();


                ControlCode = Convert.ToInt32(codeList[1], 16).ToString();
                ItemLenth = Convert.ToInt32(codeList[2], 16);

                if (ControlCode == "3")
                {
                    for (int i = 3; i < 3 + ItemLenth; i = i + 2)
                    {
                        if (KeepingDic.ContainsKey(startIndex))
                        {
                            KeepingDic[startIndex] = codeList[i] + codeList[i + 1];

                        }
                        else
                        {
                            KeepingDic.Add(startIndex, codeList[i] + codeList[i + 1]);

                        }

                        startIndex++;
                    }


                }
                else if (ControlCode == "4")
                {
                    for (int i = 3; i < 3 + ItemLenth; i = i + 2)
                    {
                        if (i + 1 > codeList.Length - 1) continue;
                        if (InputDic.ContainsKey(startIndex))
                        {
                            InputDic[startIndex] = codeList[i] + codeList[i + 1];

                        }
                        else
                        {
                            InputDic.Add(startIndex, codeList[i] + codeList[i + 1]);

                        }

                        startIndex++;

                    }
                }
                else if (ControlCode == "6")
                {
                    WriteDataFlag = true;
                }
                //ItemValue = Convert.ToInt32(ItemValue, 16).ToString();
                CalaValue = codeList[codeList.Length - 2] + codeList[codeList.Length - 1];
            }
            catch (Exception ex)
            {
                PublicHelper.WriteErrorMsg(ex);
            }
        }

        /// <summary>
        /// 计算校验码
        /// </summary>
        /// <param name="sendD"></param>
        /// <returns></returns>
        public string CRC16Calc(string sendD)
        {
            var trimString = sendD.Replace(" ", "");
            var ChangeString = "";
            for (int i = 0; i < trimString.Length; i = i + 2)
            {
                var tmpFrame = trimString.Substring(i, 2);
                ChangeString = ChangeString + tmpFrame + " ";
            }
            ChangeString = ChangeString.Substring(0, ChangeString.Length - 1);

            var splitData = ChangeString.Split(' ');
            byte[] dataBuff = new byte[splitData.Length + 2];
            for (int i = 0; i < dataBuff.Length - 2; i++)
            {
                dataBuff[i] = (byte)Convert.ToInt32(splitData[i], 16);
            }
            int CRCResult = 0xFFFF;
            int dataLen = splitData.Length + 2;
            if (splitData.Length < 2)

            {
                return "";

            }
            for (int i = 0; i < (dataLen - 2); i++)
            {
                CRCResult = CRCResult ^ dataBuff[i];//^ 异或运算
                for (int j = 0; j < 8; j++)
                {
                    if ((CRCResult & 1) == 1)

                        CRCResult = (CRCResult >> 1) ^ 0xA001;
                    else CRCResult >>= 1;
                }
            }
            dataBuff[dataLen - 1] = Convert.ToByte(CRCResult >> 8);
            dataBuff[dataLen - 2] = Convert.ToByte(CRCResult & 0xff);

            var result = "";
            for (int k = 0; k < dataBuff.Length; k++)
            {
                result = result + Convert.ToString(dataBuff[k], 16).PadLeft(2, '0').ToUpper() + " ";
            }
            result = result.Substring(0, result.Length - 1);
            return result;
        }

        /// <summary>
        /// 获取寄存器中的值赋值到探头实时模型中
        /// </summary>
        public void Get_inputChannalInfoList(Dictionary<int, GasMeter.TaskGasMeterModel> _gasMeterList)
        {
            try
            {

                realTimeValue = new Dictionary<int, GasSaveModel>();

                if (InputDic != null && RetrunEmpty == false)
                {
                    AddLog("开始解析寄存器数据--[" + InputDic.Count.ToString() + "]个");
                    int startAddress = 8;
                    int _channalIndex = 0;
                    for (int i = 0; i < InputDic.Count; i = i + 2)
                    {
                        if (InputDic.ContainsKey(i+ StartIndex) == false) continue;//判断字典是否有该地址的数据
                        #region 
                        string mainPowerState = "";
                        string backupPowerState = "";
                        string GasState = "";
                        string GasMannualState = "";
                        string GasErrorFlag = "";
                        string _gasValue = "";
                        #endregion
                        //浓度
                        if (listGasChannalConfig != null && listGasChannalConfig.Count > _channalIndex)
                        {
                            GasChannalConfig _channalConfig = listGasChannalConfig[_channalIndex];
                            _gasValue = (Convert.ToInt32(InputDic[StartIndex + i], 16) / _channalConfig.DecimalPoint).ToString();
                        }
                        else
                        {
                            _gasValue = (Convert.ToInt32(InputDic[StartIndex + i], 16) * Math.Pow(10, 2 * -1)).ToString();
                        }
                        //状态
                       var TmpGasState= Convert.ToString(Convert.ToInt16(InputDic[StartIndex + i + 1].Substring(2, 2), 16), 2).PadLeft(8, '0').Substring(4, 4);
                        #region 判断探头状态
                        if (TmpGasState[0].ToString() == "1")
                        {
                            GasState = "高警";
                        }
                        else
                        {
                            if (TmpGasState[1].ToString() == "1")
                            {
                                GasState = "低警";
                            }
                            else
                            {
                                if (TmpGasState[2].ToString() == "1")
                                {
                                    GasState = "故障";
                                }
                                else
                                {
                                    GasState = "正常";
                                }
                            }
                        }

                        #endregion
                        #region 手动计算状态
                        if (Utility.Const.GbUnit.IsCalcStateByMannual)
                        {
                            if (_gasMeterList[realTimeValue.Count + 1].GasType == "O2")
                            {
                                if (double.Parse(_gasValue) < _gasMeterList[realTimeValue.Count + 1].LowAlarmValue)
                                {
                                    GasMannualState = "低警";
                                }
                                else if (double.Parse(_gasValue) > _gasMeterList[realTimeValue.Count + 1].HighAlarmValue)
                                {
                                    GasMannualState = "高警";
                                }
                                else
                                {
                                    GasMannualState = "正常";
                                }

                            }
                            else
                            {
                                if (double.Parse(_gasValue) > _gasMeterList[realTimeValue.Count + 1].LowAlarmValue && double.Parse(_gasValue) < _gasMeterList[realTimeValue.Count + 1].HighAlarmValue)
                                {
                                    GasMannualState = "低警";
                                }
                                else if (double.Parse(_gasValue) >= _gasMeterList[realTimeValue.Count + 1].HighAlarmValue)
                                {
                                    GasMannualState = "高警";
                                }
                                else
                                {
                                    GasMannualState = "正常";
                                }
                            }
                            GasState = GasMannualState;
                        }
                        #endregion
                        double endRange = 0.0f;
                        double curGasValue = 0.0f;

                        if (double.TryParse(_gasMeterList[realTimeValue.Count + 1].EndRange, out endRange) && double.TryParse(_gasValue, out curGasValue))
                        {
                            if (endRange < curGasValue)
                            {
                                _gasValue = _gasMeterList[realTimeValue.Count + 1].EndRange;
                            }
                        }
                        realTimeValue.Add(_gasMeterList[realTimeValue.Count + 1].ChannelIndex, new GasSaveModel()
                        {
                            GasValue = _gasValue,
                            GasState = GasState,
                            OccurTime = DateTime.Now,
                            GasCurrentState = GasMannualState
                        });
                        if(realTimeValue.Count== _gasMeterList.Count)
                        {
                            break;
                        }
                        _channalIndex++;
                    }
                }

                if (realTimeValue.Count == _gasMeterList.Count)//解析数据跟配置数据一致
                {
                    lastTimerealTimeValue = realTimeValue;
                    AddLog("解析数据跟配置数据一致");
                }
                else
                {
                    AddLog("解析数据跟配置数据不一致realTimeValue.Count[" + realTimeValue.Count.ToString() + "]_gasMeterList:[" + _gasMeterList.Count + "]");
                    if (realTimeValue.Count != _gasMeterList.Count && lastTimerealTimeValue != null && lastTimerealTimeValue.Count == _gasMeterList.Count)//该次解析失败，采用上一次读取的数据
                    {
                        if (ControllerFailTime < ControllerFailMaxTime)
                        {
                            ControllerFailTime++;
                            realTimeValue = lastTimerealTimeValue;
                        }
                        else
                        {
                            //超过最大失败次数
                            AddLog("超过最大失败次数");

                            realTimeValue = new Dictionary<int, GasSaveModel>();
                            for (int i = 0; i < _gasMeterList.Count; i++)
                            {
                                realTimeValue.Add(i + 1, new GasSaveModel()
                                {
                                    OccurTime = DateTime.Now,
                                    GasCurrentState = "故障",
                                    GasState = "故障",
                                    GasValue = "0.0"
                                });
                            }
                        }



                    }
                    else if (lastTimerealTimeValue == null)
                    {
                        realTimeValue = new Dictionary<int, GasSaveModel>();
                        for (int i = 0; i < _gasMeterList.Count; i++)
                        {
                            realTimeValue.Add(i + 1, new GasSaveModel()
                            {
                                OccurTime = DateTime.Now,
                                GasCurrentState = "故障",
                                GasState = "故障",
                                GasValue = "0.0"
                            });
                        }
                    }
                    else
                    {
                        ControllerFailTime = 0;
                    }
                }


            }
            catch (Exception ex)
            {
                Utility.Helper.PublicHelper.WriteErrorMsg(ex);
            }
        }

        public void Get_keepingChannalInfoList()
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 读取探头数据
        /// </summary>
        /// <param name="_controller"></param>
        /// <returns></returns>
        public bool ReadControllerData(TaskControllerModel _controller)
        {
            bool result = false;
            try
            {
                #region ES2000_D控制器
                //0x03 读取 
                //0x01 单位 浓度比例，高字节单位，低字节浓度比例
                //地址0~7为一个通道的所有信息 ，第二个通道以此类推
                //0x00       设备信息字段     bit3~0（主电） 0:正常 1：屏蔽 2：故障    bit7~4（备电） 0:正常 1：屏蔽 2：故障    bit10~8（继电器3~1） 0:断开 1：闭合
                //0x01       设备工作状态字段  bit3~0（探头状态） 0:正常 1：低警 2：高警 3：超限 bit11~bit8 0：正常 1：故障 
                //0x02 0x03  温度
                //0x04 0x05  气体采样值
                //0x06 0x07  气体浓度
                #endregion
                //1.组帧
                SetRunStateMsg("组帧");
                ChannelDataLength = 4;
                StartIndex = 1;
                ReadLength = 4;
                SendCodeList = new List<string>();
                NeedReadLength = ChannelDataLength * _controller.ChannelCount;
                var frameStart = Convert.ToString(StartIndex, 16).PadLeft(4, '0');
                int tmpstartIndex = StartIndex;
                for (int i = 0; i < NeedReadLength; i = i + ReadLength)
                {
                    frameStart = Convert.ToString(tmpstartIndex, 16).PadLeft(4, '0');
                    var frameLenth = Convert.ToString(ReadLength, 16).PadLeft(4, '0');
                    if (i + ReadLength > NeedReadLength)
                    {
                        frameLenth = Convert.ToString(NeedReadLength - i, 16).PadLeft(4, '0'); ;
                    }
                    var tmpSendData = Convert.ToString(_controller.Address, 16).PadLeft(2, '0') + " 03 " + frameStart + frameLenth;
                    tmpSendData = CRC16Calc(tmpSendData);
                    SendCodeList.Add(tmpSendData);
                    tmpstartIndex += ReadLength;
                }
                SetRunStateMsg("组帧完毕");

                //2.发送
                RetrunEmpty = false;
                tmpstartIndex = StartIndex;
                foreach (var k in SendCodeList)
                {
                    SetRunStateMsg("发送-" + "[" + k + "]");

                    SerialHelper.SendData(k);
                    AddLog("发送-" + "[" + k + "]");
                    Thread.Sleep(SerialHelper.WaitTime);
                    bool Frameok = false;
                    int waitTime = 3;
                    while (SerialHelper.ReceivedText == string.Empty)//回复为空，循环等待3次
                    {
                        Thread.Sleep(SerialHelper.WaitTime);
                        if (waitTime <= 0)
                        {
                            Thread.Sleep(SerialHelper.WaitTime);
                            break;
                        }
                        waitTime--;
                    }
                    SetRunStateMsg("等待回复");

                    if (SerialHelper.ReceivedText != "")
                    {
                        Frameok = CheckFrame(SerialHelper.ReceivedText, "03", Convert.ToString(_controller.Address, 16).PadLeft(2, '0').ToUpper());
                    }
                    else
                    {
                        RetrunEmpty = true;
                        AddLog("收到(回复为空)-" + "[" + SerialHelper.ReceivedText + "]");
                        AddErrorLog("收到(回复为空)-" + "[" + SerialHelper.ReceivedText + "]");
                        Thread.Sleep(SerialHelper.WaitTime * 2);
                        if (SerialHelper.ReceivedText == "")
                        {
                            AddLog("继续等待依然没有回复-" + "[" + SerialHelper.ReceivedText + "]");
                            AddErrorLog("收继续等待依然没有回复-" + "[" + SerialHelper.ReceivedText + "]");
                        }
                        else
                        {
                            RetrunEmpty = false;

                        }
                    }
                    SetRunStateMsg("收到-" + "[" + SerialHelper.ReceivedText + "]");

                    if (Frameok)
                    {
                        //解析回复 放到寄存器字典
                        AddLog("收到-" + "[" + SerialHelper.ReceivedText + "]");

                        AnalyzeCode(SerialHelper.ReceivedText, tmpstartIndex);
                    }
                    else
                    {
                        if (RetrunEmpty == false)
                        {
                            //异常再等待一次，判断
                            Thread.Sleep(SerialHelper.WaitTime);
                            AddErrorLog("收到(解析格式异常)-" + "[" + SerialHelper.ReceivedText + "],等待帧完整");
                            //解析格式异常
                            Frameok = CheckFrame(SerialHelper.ReceivedText, "03", Convert.ToString(_controller.Address, 16).PadLeft(2, '0').ToUpper());
                            if (Frameok)
                            {
                                //解析回复 放到寄存器字典
                                AddLog("收到-" + "[" + SerialHelper.ReceivedText + "]");
                                AddErrorLog("继续等待后，帧完整，需要增加通讯等待时间");
                                AnalyzeCode(SerialHelper.ReceivedText, tmpstartIndex);
                            }
                            else
                            {
                                AddLog("收到(解析格式异常)-" + "[" + SerialHelper.ReceivedText + "],依旧异常");

                            }

                        }
                    }
                    SetRunStateMsg("解析通道单位完毕");

                    tmpstartIndex += ReadLength;
                }
                //3.解析通道单位浓度比例
                SetRunStateMsg("解析通道单位浓度比例");
                GetGasChannalConfig();
                SetRunStateMsg("发送读取浓度比例报文");
                #region 读取浓度
                SetRunStateMsg("组帧");
                ChannelDataLength = 2;
                StartIndex = 6;
                ReadLength = 2;
                SendCodeList = new List<string>();
                NeedReadLength = ChannelDataLength * _controller.ChannelCount;
                frameStart = Convert.ToString(StartIndex, 16).PadLeft(4, '0');
                tmpstartIndex = StartIndex;
                for (int i = 0; i < NeedReadLength; i = i + ReadLength)
                {
                    frameStart = Convert.ToString(tmpstartIndex, 16).PadLeft(4, '0');
                    var frameLenth = Convert.ToString(ReadLength, 16).PadLeft(4, '0');
                    if (i + ReadLength > NeedReadLength)
                    {
                        frameLenth = Convert.ToString(NeedReadLength - i, 16).PadLeft(4, '0'); ;
                    }
                    var tmpSendData = Convert.ToString(_controller.Address, 16).PadLeft(2, '0') + " 04 " + frameStart + frameLenth;
                    tmpSendData = CRC16Calc(tmpSendData);
                    SendCodeList.Add(tmpSendData);
                    tmpstartIndex += ReadLength;
                }
                SetRunStateMsg("组帧完毕");

                #endregion
                RetrunEmpty = false;
                tmpstartIndex = StartIndex;
                foreach (var k in SendCodeList)
                {
                    SetRunStateMsg("发送-" + "[" + k + "]");

                    SerialHelper.SendData(k);
                    AddLog("发送-" + "[" + k + "]");
                    Thread.Sleep(SerialHelper.WaitTime);
                    bool Frameok = false;
                    int waitTime = 3;
                    while (SerialHelper.ReceivedText == string.Empty)//回复为空，循环等待3次
                    {
                        Thread.Sleep(SerialHelper.WaitTime);
                        if (waitTime <= 0)
                        {
                            Thread.Sleep(SerialHelper.WaitTime);
                            break;
                        }
                        waitTime--;
                    }
                    SetRunStateMsg("等待回复");

                    if (SerialHelper.ReceivedText != "")
                    {
                        Frameok = CheckFrame(SerialHelper.ReceivedText, "04", Convert.ToString(_controller.Address, 16).PadLeft(2, '0').ToUpper());
                    }
                    else
                    {
                        RetrunEmpty = true;
                        AddLog("收到(回复为空)-" + "[" + SerialHelper.ReceivedText + "]");
                        AddErrorLog("收到(回复为空)-" + "[" + SerialHelper.ReceivedText + "]");
                        Thread.Sleep(SerialHelper.WaitTime * 2);
                        if (SerialHelper.ReceivedText == "")
                        {
                            AddLog("继续等待依然没有回复-" + "[" + SerialHelper.ReceivedText + "]");
                            AddErrorLog("收继续等待依然没有回复-" + "[" + SerialHelper.ReceivedText + "]");
                        }
                        else
                        {
                            RetrunEmpty = false;

                        }
                    }
                    SetRunStateMsg("收到-" + "[" + SerialHelper.ReceivedText + "]");

                    if (Frameok)
                    {
                        //解析回复 放到寄存器字典
                        AddLog("收到-" + "[" + SerialHelper.ReceivedText + "]");

                        AnalyzeCode(SerialHelper.ReceivedText, tmpstartIndex);
                    }
                    else
                    {
                        if (RetrunEmpty == false)
                        {
                            //异常再等待一次，判断
                            Thread.Sleep(SerialHelper.WaitTime);
                            AddErrorLog("收到(解析格式异常)-" + "[" + SerialHelper.ReceivedText + "],等待帧完整");
                            //解析格式异常
                            Frameok = CheckFrame(SerialHelper.ReceivedText, "04", Convert.ToString(_controller.Address, 16).PadLeft(2, '0').ToUpper());
                            if (Frameok)
                            {
                                //解析回复 放到寄存器字典
                                AddLog("收到-" + "[" + SerialHelper.ReceivedText + "]");
                                AddErrorLog("继续等待后，帧完整，需要增加通讯等待时间");
                                AnalyzeCode(SerialHelper.ReceivedText, tmpstartIndex);
                            }
                            else
                            {
                                AddLog("收到(解析格式异常)-" + "[" + SerialHelper.ReceivedText + "],依旧异常");

                            }

                        }
                    }
                    SetRunStateMsg("解析通道单位完毕");

                    tmpstartIndex += ReadLength;
                }
                Get_inputChannalInfoList(_controller.Dic_GasMeter);
                SetRunStateMsg("赋值实时数据完毕");

                //4.赋值实时数据
                SendCodeList.Clear();
            }
            catch (Exception ex)
            {
                PublicHelper.WriteErrorMsg(ex);
            }
            return result;
        }
        /// <summary>
        /// 判断接受报文是否为完整的帧
        /// </summary>
        /// <param name="Code"></param>
        /// <returns></returns>
        private bool CheckFrame(string Code, string CodeFlag, string ControllerAddress)
        {
            bool result = true;
            try
            {
                var trimString = Code.Replace(" ", "");
                var ChangeString = "";
                for (int i = 0; i < trimString.Length; i = i + 2)
                {
                    var tmpFrame = trimString.Substring(i, 2);
                    ChangeString = ChangeString + tmpFrame + " ";
                }
                if (ChangeString.Length == 0)
                {
                    //回复为空
                    return false;
                }
                ChangeString = ChangeString.Substring(0, ChangeString.Length - 1);
                //01 03 14 00 07 00 0A 00 0A 00 07 00 07 00 07 00 07 00 07 00 0A 00 07 2F 75
                //判断帧长
                var codeList = ChangeString.Split(' ');
                if (codeList.Length < 3)
                {
                    //帧不完整
                    return false;
                }
                //判断是否为当前控制器的回复报文
                if (codeList[0] != ControllerAddress)
                {
                    //不是当前控制器的回复报文
                    return false;
                }
                if (codeList[1] != CodeFlag)
                {
                    //不是当前控制器报文的请求类型
                    return false;
                }
                int codeLenth = Convert.ToInt32(codeList[2], 16);
                if (codeList.Length != codeLenth + 5)
                {
                    //帧不完整

                    return false;
                }
                //判断校验
                var needCrcCode = "";
                for (int i = 0; i < codeList.Length - 2; i++)
                {
                    needCrcCode += codeList[i];
                }
                needCrcCode = CRC16Calc(needCrcCode);
                if (trimString != needCrcCode.Replace(" ", ""))
                {
                    //校验码不对

                    return false;
                }
            }
            catch (Exception ex)
            {
                PublicHelper.WriteErrorMsg(ex);
                result = false;
            }
            return result;
        }
        public bool ReadGasValueAndState(TaskGasMeterModel _controllerList)
        {
            throw new NotImplementedException();
        }

        public bool Set_GasMeterNoVoice(TaskControllerModel _controller)
        {
            //06 00 09 C0 40
            bool result = true;
            try
            {
                if (IsCanSet == false) return result;
                //消音 复位 寄存器地址 0x0002 ,06功能码，0x0001 为 消音 0x0002 为 复位
                List<string> SendList = new List<string>();
                var tmpSendData = Convert.ToString(_controller.Address, 16).PadLeft(2, '0') + " 06 " + "00 09 " + "C0 40 ";
                tmpSendData = CRC16Calc(tmpSendData);
                SendList.Add(tmpSendData);
                for (int i = 0; i < SendList.Count; i++)
                {
                    SerialHelper.SendData(SendList[i]);
                    System.Threading.Thread.Sleep(SerialHelper.WaitTime);
                    //ShowLogMessage(string.Format("总线{2}-控制器{1}=>03=》收到报文{0}", _serialHelper.ReceivedText, _controllerModel.ControllerAddress, _controllerModel.TotalLineNumber));
                    if (SerialHelper.ReceivedText == string.Empty)
                    {
                        System.Threading.Thread.Sleep(SerialHelper.WaitTime);
                        if (SerialHelper.ReceivedText == string.Empty)
                        {
                            continue;
                        }
                    }
                    bool checkCodeFlag = false;
                    for (int w = 0; w < 5; w++)
                    {
                        checkCodeFlag = SerialHelper.ReceivedText == string.Empty;
                        if (checkCodeFlag)
                        {
                            break;
                        }
                        SerialHelper.SendData(SendList[i]);
                        System.Threading.Thread.Sleep(SerialHelper.WaitTime);
                    }
                }

            }
            catch (Exception ex)
            {
                PublicHelper.WriteErrorMsg(ex.ToString());
                result = false;
            }
            return result;
        }

        public bool Set_GasMeterReSet(TaskControllerModel _controller)
        {
            //06 00 09 E0 20
            bool result = true;
            try
            {
                if (IsCanSet == false) return result;
                //消音 复位 寄存器地址 0x0002 ,06功能码，0x0001 为 消音 0x0002 为 复位
                List<string> SendList = new List<string>();
                var tmpSendData = Convert.ToString(_controller.Address, 16).PadLeft(2, '0') + " 06 " + "00 09 " + "E0 20 ";
                tmpSendData = CRC16Calc(tmpSendData);
                SendList.Add(tmpSendData);
                for (int i = 0; i < SendList.Count; i++)
                {
                    //06 06 00 09 E0 20 10 67
                    SerialHelper.SendData(SendList[i]);
                    System.Threading.Thread.Sleep(SerialHelper.WaitTime);
                    //ShowLogMessage(string.Format("总线{2}-控制器{1}=>03=》收到报文{0}", _serialHelper.ReceivedText, _controllerModel.ControllerAddress, _controllerModel.TotalLineNumber));
                    //回复06 06 00 09 E0 20 10 67
                    if (SerialHelper.ReceivedText == string.Empty)
                    {
                        System.Threading.Thread.Sleep(SerialHelper.WaitTime);
                        if (SerialHelper.ReceivedText == string.Empty)
                        {
                            continue;
                        }
                    }
                    bool checkCodeFlag = false;
                    for (int w = 0; w < 5; w++)
                    {
                        checkCodeFlag = SerialHelper.ReceivedText != string.Empty;
                        if (checkCodeFlag)
                        {
                            break;
                        }
                        SerialHelper.SendData(SendList[i]);
                        System.Threading.Thread.Sleep(SerialHelper.WaitTime);
                    }
                }

            }
            catch (Exception ex)
            {
                PublicHelper.WriteErrorMsg(ex.ToString());
                result = false;
            }
            return result;
        }

        /// <summary>
        /// 显示日志
        /// </summary>
        /// <param name="msg"></param>
        public void AddLog(string msg)
        {
            if (Utility.Const.GbUnit.IsShowCommunicationLog && int.Parse(MainAddress) == Utility.Const.GbUnit.ShowLogControllerAddressIndex && int.Parse(TotalLineNumber) == Utility.Const.GbUnit.ShowLogControllerTotalLine)
            {
                List<string> list = new List<string>();
                list.Add("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "]" + msg);
                list.Add(TotalLineNumber);
                list.Add(MainAddress);
                AddLogEventHandler(list, new EventArgs());
            }
        }
        private void SetRunStateMsg(string _message)
        {

            List<string> list = new List<string>();
            list.Add(TotalLineNumber);
            list.Add(_message);
            AddRunStateModelEventHandler(list, new EventArgs());
        }
        /// <summary>
        /// 显示错误日志
        /// </summary>
        /// <param name="msg"></param>
        public void AddErrorLog(string msg)
        {
            SetRunStateMsg(msg);
            AddErrorLogEventHandler("总线[" + TotalLineNumber + "]-地址[" + MainAddress + "]" + "[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "]" + msg, new EventArgs());

        }

        #region this Interface  private Function
        /// <summary>
        /// 转换报文为数值
        /// </summary>
        /// <param name="changeKey"></param>
        /// <returns></returns>
        private string ChangeByteArrayToFloat(string changeKey)
        {
            string result = "";
            try
            {
                byte[] bytearry = new byte[4];
                bytearry[3] = (byte)Convert.ToInt32(changeKey.Substring(0, 2), 16);
                bytearry[2] = (byte)Convert.ToInt32(changeKey.Substring(2, 2), 16);
                bytearry[1] = (byte)Convert.ToInt32(changeKey.Substring(4, 2), 16);
                bytearry[0] = (byte)Convert.ToInt32(changeKey.Substring(6, 2), 16);
                var changeValue = BitConverter.ToSingle(bytearry, 0);
                result = changeValue.ToString("0.00");
            }
            catch (Exception ex)
            {


            }
            return result;
        }
        /// <summary>
        /// 解析通道的单位
        /// </summary>
        private void GetGasChannalConfig()
        {
            try
            {
                int startItemAddress = 1;
                if (KeepingDic != null)
                {
                    for (int i = 0; i < KeepingDic.Count; i = i + 4)
                    {
                        int tmpDataLength = 0;
                        int tmpDivideFactor = 0;
                        int tmpDecimalPoint = 0;
                        var _dataConfig = Convert.ToString(Convert.ToInt32(KeepingDic[startItemAddress + i], 16), 2).PadLeft(16, '0').Substring(8, 8);
                        tmpDecimalPoint = Convert.ToInt32(_dataConfig, 2);
                        listGasChannalConfig.Add(new GasChannalConfig()
                        {
                            DataLength = tmpDataLength,
                            DivideFactor = tmpDivideFactor,
                            DecimalPoint = tmpDecimalPoint,
                        });

                    }
                }    
              

            }
            catch (Exception ex)
            {
                PublicHelper.WriteErrorMsg(ex);
            }
        }
        #endregion
    }
}
